﻿using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Middleware
{
    public static class AuthenticationMiddlewareExtensions
    {
        public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AuthenticationMiddleware>();
        }
    }

    public class AuthenticationMiddleware
    {
        private readonly RequestDelegate _next;

        public AuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, AuthService authService)
        {
            if (context.User.Identity?.IsAuthenticated != true)
            {
                await _next(context);
                return;
            }

            var username = context.User.Identity.Name;
            var user = await authService.GetUserByUsernameAsync(username);

            if (user == null)
            {
                await _next(context);
                return;
            }

            context.Items["User"] = user;

            await _next(context);
        }
    }
}